package com.kb.service.impl.crm;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.config.XxlJobConfig;
import com.kb.entity.crm.Customer;
import com.kb.entity.crm.CustomerAddress;
import com.kb.entity.crm.LinkManOfCustomer;
import com.kb.entity.kbidm.*;
import com.kb.mapper.sqlServer.kbidm.*;
import com.kb.service.crm.CrmService;
import com.kb.service.crm.KBIDMService;
import com.kb.util.MessageUtil;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

@Service
@DS("KBIDM")
@Slf4j
public class KBIDMServiceImpl extends ServiceImpl<KbCustAddressMapper, KbCustAddress> implements KBIDMService {
    //todo 环境切换
//    String url = "https://mall.kingbrother.com";
    //测试环境
//    String url = "https://dev.mall.kingbrother.com";
//    String url = "http://192.168.21.100:5000";

    @Value("${kbi.url}")
    private String url;

    @Resource
    private CrmService crmService;
    @Resource
    private KbInvoicingMapper invoicingMapper;
    @Resource
    private KbSysCustMapper sysCustMapper;
    @Resource
    private KbCustAddressMapper custAddressMapper;
    @Resource
    private KBSysCust sysCustService;
    @Resource
    private KbTechnicalMapper technicalMapper;
    @Resource
    private SysUserMapper sysUserMapper;



    @Override
//    @DSTransactional
    public void crmCustInfo2IDM(List<String> codeList) throws ParseException {
        List<Customer> customerList = new ArrayList<>();
        int i = 0;
        if (CollectionUtils.isEmpty(codeList)) {
            //查询最近两天修改的数据和syn_order_system = 1的数据
            customerList = crmService.queryCustomerByParams(1);
        } else {
            customerList = crmService.queryCustomerByCode(codeList);
        }
        XxlJobHelper.log("此次更新客户数量：" + customerList.size());
        if (CollectionUtils.isNotEmpty(customerList)) {
            for (Customer customer : customerList) {
                //新建 i 计数
                i++;
                log.info("第{}条数据，客代{}", i, customer.getCustcode());
                XxlJobHelper.log("第{}条数据，客代{}", i, customer.getCustcode());

                //基本信息
                KbSysCust kbSysCust = new KbSysCust();
                String custId = UUID.randomUUID().toString();
                BeanUtils.copyProperties(customer, kbSysCust);

                kbSysCust.setfId(custId);
                kbSysCust.setfRecid(customer.getRecid());
                kbSysCust.setCustAddress(customer.getCustaddress());
                kbSysCust.setSysuserid(customer.getSysuserid());
                //付款周期
                kbSysCust.setPaymentTermId(customer.getPaymenttermid());
                //行业
                String industry = crmService.queryCustomerIndustryById(customer.getRecid().toString());
                kbSysCust.setIndustryType(industry);
                kbSysCust.setIsactivate(1);
                kbSysCust.setfDeletemark(0);
                //先查询kbidm方是否有值，有则更新，无则插入
                KbSysCust customerById = sysCustMapper.queryCustomerById(customer.getRecid());
                //客户账号 查询是否有，有就跳过 无就新增
                SysUser sysUser = sysUserMapper.querySysUserById(customer.getRecid());
                if (Objects.isNull(sysUser)) {
                    //调新增用户接口 生成客户用户
                    HashMap<String, Object> paramMap = new HashMap<>();
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");

                    String custUserId = UUID.randomUUID().toString();
                    paramMap.put("account", customer.getCustcode() + "01");
                    paramMap.put("Id", custUserId);
                    paramMap.put("PassWord", "Kb" + customer.getCustcode() + "*");
                    paramMap.put("realName", customer.getCustname());
                    paramMap.put("nickName", customer.getCustnickname());
                    paramMap.put("mobilePhone", customer.getCusttel());
                    paramMap.put("email", customer.getCustemail());
                    paramMap.put("crmid", customer.getRecid());
                    paramMap.put("sysuserId", customer.getSysuserid());

                    HttpResponse response = null;
                    try {
//                        String userUrl = url + "/api/AccountAPI/CRM2IDMUser";
                        String userUrl = url + "/api/ClientsDataAPI/CRM2IDMUser";
                        response = HttpRequest.post(userUrl)
                                .body(JSONUtil.toJsonStr(paramMap))
                                .addHeaders(headers)

                                .timeout(30000)
                                .execute();
                    } catch (Exception e) {
                        XxlJobHelper.log("调用用户新增接口异常：", e.getMessage());
                        throw new RuntimeException(e);
                    }
                    log.info("请求状态: {}, 参数: {}, 返回数据: {}",
                            response.getStatus(), JSONUtil.toJsonStr(paramMap), response.body());
                    XxlJobHelper.log("请求状态: {}, 参数: {}, 返回数据: {}",
                            response.getStatus(), JSONUtil.toJsonStr(paramMap), response.body());
                    //用户和客户关系
                    kbSysCust.setfUserid(custUserId);
                }
                if (Objects.isNull(customerById)) {
                    sysCustMapper.insert(kbSysCust);
                    XxlJobHelper.log("新增客户：" + JSONUtil.parse(kbSysCust));
                } else {

                    kbSysCust.setfId(customerById.getfId());
                    custId = customerById.getfId();
                    sysCustMapper.updateById(kbSysCust);
                    XxlJobHelper.log("更新客户：" + JSONUtil.parse(kbSysCust));
                }
                /**
                 *  ===============================================================================================================
                 */
                //开票抬头信息
                KbInvoicing kbInvoicing = new KbInvoicing();
                BeanUtils.copyProperties(customer, kbInvoicing);

                kbInvoicing.setTaxpayerNumber(customer.getTariff());
                kbInvoicing.setInvoiceHeader(customer.getBillingcompany());
                kbInvoicing.setDepositBank(customer.getBank());
                kbInvoicing.setMailingaddress(customer.getBillingadd());
                kbInvoicing.setBankAccount(customer.getAccount());
                kbInvoicing.setStatus(1);


                kbInvoicing.setfCustid(custId);
                kbInvoicing.setfId(UUID.randomUUID().toString());
                kbInvoicing.setfDeletemark(0);
                kbInvoicing.setfRecid(customer.getRecid());
                //先查询kbidm方是否有值，有则更新，无则插入
                KbInvoicing invoiceById = invoicingMapper.queryInvoiceById(customer.getRecid());
                if (Objects.isNull(invoiceById)) {
                    invoicingMapper.insert(kbInvoicing);
                } else {
                    kbInvoicing.setfId(invoiceById.getfId());
                    invoicingMapper.updateById(kbInvoicing);
                }
                //地址信息
                List<CustomerAddress> addressList = crmService.queryCustAddress(customer.getRecid());
                if (CollectionUtils.isNotEmpty(addressList)) {
                    for (CustomerAddress customerAddress : addressList) {
                        KbCustAddress kbCustAddress = new KbCustAddress();
                        BeanUtils.copyProperties(customerAddress, kbCustAddress);

                        kbCustAddress.setfId(UUID.randomUUID().toString());
                        kbCustAddress.setfCustid(custId);
                        kbCustAddress.setContactNumber(customerAddress.getTel());
                        kbCustAddress.setRemark(customerAddress.getNote());
                        kbCustAddress.setfRecid(customerAddress.getRecid());
                        kbCustAddress.setIsAcquiesce(0);
                        kbCustAddress.setIsAcquiesce(1);

                        kbCustAddress.setfDeletemark(0);
                        kbCustAddress.setDetailedAddress(customerAddress.getAddress());
                        //先查询kbidm方是否有值，有则更新，无则插入
                        KbInvoicing queryAddressById = custAddressMapper.queryAddressById(customerAddress.getRecid());
                        if (Objects.isNull(queryAddressById)) {
                            custAddressMapper.insert(kbCustAddress);
                        } else {
                            kbCustAddress.setfId(queryAddressById.getfId());
                            custAddressMapper.updateById(kbCustAddress);
                        }
                    }
                }
                //联系人信息
                List<LinkManOfCustomer> linkManOfCustomer = crmService.queryContacts(customer.getRecid());
                if (CollectionUtils.isNotEmpty(linkManOfCustomer)) {
                    for (LinkManOfCustomer manOfCustomer : linkManOfCustomer) {
                        KbTechnicalContacts LinkManOfCustomer = technicalMapper.queryContactsById(manOfCustomer.getRecId());
                        //有则更新，无则插入
                        KbTechnicalContacts kbTechnicalContacts = new KbTechnicalContacts();
                        BeanUtils.copyProperties(manOfCustomer, kbTechnicalContacts);
                        kbTechnicalContacts.setfRecId(manOfCustomer.getRecId());
                        kbTechnicalContacts.setName(manOfCustomer.getLinkManName());
                        kbTechnicalContacts.setPhone(manOfCustomer.getMobile());
                        kbTechnicalContacts.setfDeleteMark(false);
                        kbTechnicalContacts.setDefault(true);
                        kbTechnicalContacts.setfCustId(kbSysCust.getfId());
                        if (Objects.isNull(LinkManOfCustomer)) {
                            kbTechnicalContacts.setfId(UUID.randomUUID().toString());
                            technicalMapper.insert(kbTechnicalContacts);
                        } else {
                            kbTechnicalContacts.setfId(LinkManOfCustomer.getfId());
                            technicalMapper.updateById(kbTechnicalContacts);
                        }

                    }
                }

                /**
                 *  ===============================================================================================================
                 */
            }
        }
        //请求电子钱包接口
        HttpRequest.get(url + "/api/AccountAPI/GenerateWallet")
                .timeout(10000)
                .execute();
    }

    @Override
    public void crmCustBaseInfo2IDM(List<String> codeList) throws ParseException {
        //查询中台的客户数据
        List<KbSysCust> custList = sysCustMapper.selectList(null);
        //分组  500一组
        List<List<KbSysCust>> partition = ListUtils.partition(custList, 500);
        for (List<KbSysCust> kbSysCusts : partition) {
            for (KbSysCust customer : kbSysCusts) {
                Long recId = customer.getfRecid();
                if (Objects.nonNull(recId)) {
                    //查询行业信息
                    String industry = crmService.queryCustomerIndustryById(recId.toString());
                    System.out.println(customer.getCustcode()   +"： " + industry);
                    customer.setIndustryType(industry);
                }
            }
            sysCustService.updateBatchById(kbSysCusts);
        }
    }

    @Override
    public Long kbeCustInfo2Crm(KbSysCust customer) {

        log.info("方法：kbeCustInfo2Crm， 参数： " + JSONUtil.parse(customer));
        Customer crmCustomer = new Customer();
        BeanUtils.copyProperties(customer, crmCustomer);
        crmCustomer.setRecid(customer.getfRecid());
        crmService.insertOrUpdateCustomer(crmCustomer);

        return crmCustomer.getRecid();
    }

    @Override
    public Long kbeInvoice2Crm(KbInvoicing invoicing) {
        log.info("方法：KbInvoicing， 参数： " + JSONUtil.parse(invoicing));
        Customer crmCustomer = new Customer();
        BeanUtils.copyProperties(invoicing, crmCustomer);
        crmCustomer.setRecid(invoicing.getfRecid()).setTariff(invoicing.getTaxpayerNumber()).setBank(invoicing.getDepositBank())
                .setBillingadd(invoicing.getContactAddress()).setBillingcompany(invoicing.getInvoiceHeader());

        crmService.insertOrUpdateCustomer(crmCustomer);
        return crmCustomer.getRecid();
    }

    @Override
    public Long kbeAddress2Crm(KbCustAddress address) {
        log.info("方法：kbeAddress2Crm， 参数： " + JSONUtil.parse(address));
        CustomerAddress customerAddress = new CustomerAddress();
        BeanUtils.copyProperties(address, customerAddress);
        customerAddress.setCustomerid(address.getfCustid())
                .setTel(address.getContactNumber()).setAddress(address.getDetailedAddress()).setSort(0);
        customerAddress.setAddress(address.getDetailedAddress()).setTel(address.getContactNumber()).setCustomerid(address.getCustomerId())
                .setCountryid(1);
        //区别编辑
        if (Objects.nonNull(address.getfRecid())){
            customerAddress.setRecid(address.getfRecid());
        }
        crmService.insertOrUpdateAddress(customerAddress);

        return customerAddress.getRecid();
    }

    @Override
    public Long kbeContacts2Crm(KbTechnicalContacts manOfCustomer) {
        try {
            log.info("方法：kbeContacts2Crm， 参数： " + JSONUtil.parse(manOfCustomer));
            if (Objects.isNull(manOfCustomer.getfCustId())) {
                throw new RuntimeException("fCustId不能为空");
            }
            LinkManOfCustomer linkManOfCustomer = new LinkManOfCustomer();
            BeanUtils.copyProperties(manOfCustomer, linkManOfCustomer);
            linkManOfCustomer
                    .setLinkManName(manOfCustomer.getName())
                    .setNickName(manOfCustomer.getName())
                    .setMobile(manOfCustomer.getPhone());
            linkManOfCustomer.setCustomerId(manOfCustomer.getfCustId());
            //带了fRecId则为编辑
            if (Objects.nonNull(manOfCustomer.getfRecId())){
                linkManOfCustomer.setRecId(manOfCustomer.getfRecId());
            }
            crmService.insertOrUpdateContacts(linkManOfCustomer);

            return linkManOfCustomer.getRecId();
        } catch (BeansException e) {
            MessageUtil.sentMessage("23988", "KBE同步技术联系人失败", "参数：" + JSONUtil.parse(manOfCustomer) + "/n异常：" + e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
